﻿using AutoMapper;
using MediatR;
using Traceable.App.Application.Command.Slaughter;
using Traceable.Domian;
using Traceable.ErrorCode;
using Traceable.Infastructure;

namespace Traceable.App.Application.Handler.Slaughter
{
    public class SeaveSlaugtherHandler : IRequestHandler<SeaveSlaugtherCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Slaughter_Table> _slaughterRepository;
        private readonly IMapper _mapper;

        public SeaveSlaugtherHandler(IBaseRepository<Slaughter_Table> slaughterRepository, IMapper mapper)
        {
            _slaughterRepository = slaughterRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 设置屠宰信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(SeaveSlaugtherCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int>result = new ApiResult<int>();

            var slaughter = _slaughterRepository.GetAll().Where(p =>p.Batch_Id==request.Batch_Id &&!p.IsDelete).FirstOrDefault();

            if (slaughter == null)
            {
                var model = _mapper.Map<Slaughter_Table>(request);
                model.CreateTime = DateTime.Now;
                model.Creater = "张三";
                model.UpdateTime = null;
                var res = _slaughterRepository.Add(model);
                if (res > 0)
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "添加成功";
                    return Task.FromResult(result);
                }
                else
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "添加失败";
                    return Task.FromResult(result);
                }

            }
            else
            {
                slaughter = _mapper.Map(request, slaughter);
                var res = _slaughterRepository.Update(slaughter);
                if (res > 0)
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "修改成功";
                    return Task.FromResult(result);
                }
                else
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "修改失败";
                    return Task.FromResult(result);
                }
            }
        }
    }
}
